package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    public static final short MATERIAL_TYPE_IMAGE = 0;
    public static final short MATERIAL_IS_COLLECTION = 0;

    /**
     * 上传图片到minio，并将数据保存到数据
     * @param multipartFile
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 0. 校验数据
        if (multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            // 1. 上传图片到minio
            // 获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();  // a.b.jpg
            // 获取原始扩展名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-", "");
            String url = fileStorageService.uploadImgFile("", fileName + suffix, multipartFile.getInputStream());
            // 2. 向素材表中保存数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(url);
            wmMaterial.setType(MATERIAL_TYPE_IMAGE);
            wmMaterial.setIsCollection(MATERIAL_IS_COLLECTION);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            // 3. 返回响应结果
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 自媒体素材分页条件查询
     *
     * @param dto
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2. 分页条件查询
        // 2.1 设置分页参数
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        // 2.2 设置查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        // 2.2.1 是否收藏
        lambdaQueryWrapper.eq(dto.getIsCollection() != 0,WmMaterial::getIsCollection,dto.getIsCollection());
        // 2.2.2 只查询登录用户的素材
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        // 2.2.3 按照时间降序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        this.page(page,lambdaQueryWrapper);
        // 3. 封装并返回响应结果
        List<WmMaterial> data = page.getRecords();
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setData(data);
        return responseResult;
    }
}
